32장 String


String 생성자 함수

표준 빌트인 객체인 String 객체는 생성자 함수 객체이다. → new 연산자로 String 인스턴스 생성할 수 있다.

new연산으로 생성하면 래퍼 객체를 생성

const strObj = new String('Lee');
console.log(strObj);
// String {0: "L", 1: "e", 2: "e", length: 3, \[\[PrimitiveValue]]: "Lee"}

프로퍼티 [[PrimitivaValue]]는 내부 슬롯 [[StringData]]을 가르킨다.

String 래퍼 객체는 배열처럼 length 프로퍼티와 인덱스를 프로퍼티키로, 각 문자를 프로퍼티 값으로 가지는 유사 배열 객체이다.
그래서 배열과 유사하게 인덱스로 문자열의 문자에 접근가능
하지만 원시값이므로 변경할 수는 없다.

console.log(strObj[0]); // L
// 문자열은 원시값이므로 변경할 수 없다. 이때 에러가 발생하지 않는다.
strObj[0] = 'S';
console.log(strObj); // 'Lee'

String생성자 함수의 인수로 문자열 아닌 값 전달하면 문자열로 강제 변환해서 할당해서 래퍼객체를 생성한다.

let strObj = new String(123);
console.log(strObj);
// String {0: "1", 1: "2", 2: "3", length: 3, [[PrimitiveValue]]: "123"}

strObj = new String(null);
console.log(strObj);
// String {0: "n", 1: "u", 2: "l", : "l", length: 4, [[PrimitiveValue]]: "null"}

length 프로퍼티

문자열의 문자 개수를 반환한다.

'Hello'.length;    // -> 5
'안녕하세요!'.length; // -> 6

String 메서드

배열에는 원본 배열을 변경하는 메서드가 있는 반면에, 문자열값은 원시값이기에, String메서드들은 새로운 문자열을 만들어서 반환한다.

따라서 String 래퍼 객체는 읽기 전용 객체로 제공된다.

console.log(Object.getOwnPropertyDescriptors(strObj));
/* String 래퍼 객체는 읽기 전용 객체다. 즉, writable 프로퍼티 어트리뷰트 값이 false다.
{
  '0': { value: 'L', writable: false, enumerable: true, configurable: false },
  '1': { value: 'e', writable: false, enumerable: true, configurable: false },
  '2': { value: 'e', writable: false, enumerable: true, configurable: false },
  length: { value: 3, writable: false, enumerable: false, configurable: false }
}
*/

String.prototype.indexOf

문자열 검색해서 첫 번째 인덱스 반환. 없으면 -1 반환.
2번째 인자로 어느 인덱스에서 부터 검색 시작할지 지정할 수 있음.

// 문자열 str의 인덱스 3부터 'l'을 검색하여 첫 번째 인덱스를 반환한다.
str.indexOf('l', 3); // -> 3

정규표현식과 매칭되는 문자열을 검색하여 인덱스 반환. 실패하면 -1 반환

const str = 'Hello world';

// 문자열 str에서 정규 표현식과 매치하는 문자열을 검색하여 일치하는 문자열의 인덱스를 반환한다.
str.search(/o/); // -> 4
str.search(/x/); // -> -1

String.prototype.includes

문자열이 포함되어있는지 확인해서 true, false 반환
마찬가지로 검색 시작할 인덱스 지정가능.

const str = 'Hello world';

// 문자열 str의 인덱스 3부터 'l'이 포함되어 있는지 확인
str.includes('l', 3); // -> true
str.includes('H', 3); // -> false

String.prototype.startsWith

특정 문자열로 시작하는지 확인하여 true, false 반환

// 문자열 str의 인덱스 5부터 시작하는 문자열이 ' '로 시작하는지 확인
str.startsWith(' ', 5); // -> true

String.prototype.endWith

특정 문자열이 끝나는지 확인하여 true, false 반환.

const str = 'Hello world';

// 문자열 str이 'ld'로 끝나는지 확인
str.endsWith('ld'); // -> true
// 문자열 str이 'x'로 끝나는지 확인
str.endsWith('x'); // -> false

String.prototype.charAt

인수로 받은 인덱스에 위치한 문자를 반환
문자열 범위 넘어가는 경우 빈문자열 반환

const str = 'Hello';

for (let i = 0; i < str.length; i++) {
  console.log(str.charAt(i)); // H e l l o
}

String.prototype.subString

인수로 전달받은 인덱스 만큼의 문자열을 반환

const str = 'Hello World';

// 인덱스 1부터 인덱스 4 이전까지의 부분 문자열을 반환한다.
str.substring(1, 4); // -> ell

#String.prototype.indexOf 와 함께 사용하면 특정 문자열을 기준으로 앞뒤에 위치한 부분문자열을 가져올 수 있다.

const str = 'Hello World';

// 스페이스를 기준으로 앞에 있는 부분 문자열 취득
str.substring(0, str.indexOf(' ')); // -> 'Hello'

// 스페이스를 기준으로 뒤에 있는 부분 문자열 취득
str.substring(str.indexOf(' ') + 1, str.length); // -> 'World'

String.prototype.slice

substring과 동일하게 동작하는데, 음수를 인수로 전달할 수 있다. 음수의 의미는 뒤에서부터.

const str = 'hello world';

// substring과 slice 메서드는 동일하게 동작한다.
// 0번째부터 5번째 이전 문자까지 잘라내어 반환
str.substring(0, 5); // -> 'hello'
str.slice(0, 5); // -> 'hello'

// 인덱스가 2인 문자부터 마지막 문자까지 잘라내어 반환
str.substring(2); // -> 'llo world'
str.slice(2); // -> 'llo world'

// 인수 < 0 또는 NaN인 경우 0으로 취급된다.
str.substring(-5); // -> 'hello world'
// slice 메서드는 음수인 인수를 전달할 수 있다. 뒤에서 5자리를 잘라내어 반환한다.
str.slice(-5); // ⟶ 'world'

String.prototype.toUpperCase / toLowerCase

문자열을 모두 대문자 소문자로 바꿈

const str = 'Hello World!';

str.toUpperCase(); // -> 'HELLO WORLD!'
str.toLowerCase(); // -> 'hello world!'

String.prototype.trim

문자열 앞뒤에 있는 공백문자를 제거한다.

const str = '   foo  ';

str.trim(); // -> 'foo'

trimStart 와 trimEnd도 추가되었다.

const str = '   foo  ';

// String.prototype.{trimStart,trimEnd} : Proposal stage 4
str.trimStart(); // -> 'foo  '
str.trimEnd();   // -> '   foo'

String.prototype.replace

전달받은 문자열 또는 정규표현식로 대체해서 반환

const str = 'Hello world';

// str에서 첫 번째 인수 'world'를 검색하여 두 번째 인수 'Lee'로 치환한다.
str.replace('world', 'Lee'); // -> 'Hello Lee'

#String.prototype.trim 대신에 Replace를 이용해서 공백을 제거할 수도 있다.

const str = '   foo  ';

// 첫 번째 인수로 전달한 정규 표현식에 매치하는 문자열을 두 번째 인수로 전달한 문자열로 치환한다.
str.replace(/\s/g, '');   // -> 'foo'
str.replace(/^\s+/g, ''); // -> 'foo  '
str.replace(/\s+$/g, ''); // -> '   foo'

String.prototype.repeat

대상 문자열을 인수만큼 반복해서 연결한 새로운 문자열 반환.

const str = 'abc';

str.repeat();    // -> ''
str.repeat(0);   // -> ''
str.repeat(1);   // -> 'abc'
str.repeat(2);   // -> 'abcabc'
str.repeat(2.5); // -> 'abcabc' (2.5 → 2)
str.repeat(-1);  // -> RangeError: Invalid count value

String.prototype.split

전달된 문자여 또는 정규표현식으로 나눈다.
나누어진 문자열을 단일 요소로 하는 배열을 반환한다.

const str = 'How are you doing?';

// 공백으로 구분(단어로 구분)하여 배열로 반환한다.
str.split(' '); // -> ["How", "are", "you", "doing?"]

// \s는 여러 가지 공백 문자(스페이스, 탭 등)를 의미한다. 즉, [\t\r\n\v\f]와 같은 의미다.
str.split(/\s/); // -> ["How", "are", "you", "doing?"]

// 인수로 빈 문자열을 전달하면 각 문자를 모두 분리한다.
str.split(''); // -> ["H", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u", " ", "d", "o", "i", "n", "g", "?"]

// 인수를 생략하면 대상 문자열 전체를 단일 요소로 하는 배열을 반환한다.
str.split(); // -> ["How are you doing?"]

배열을 반환하는 점을 이용하여 문자열을 역순으로 뒤집을 수 있다.

// 인수로 전달받은 문자열을 역순으로 뒤집는다.
function reverseString(str) {
  return str.split('').reverse().join('');
}

reverseString('Hello world!'); // -> '!dlrow olleH'

reference